# coding=utf-8
import base64
import urllib
import uuid

from flask import Flask
from flask import request, json
import easyocr
import os

app = Flask(__name__)
reader = easyocr.Reader(['ch_sim', 'en'], gpu=False)

# 接口的入参是验证码图片的base64
@app.route('/ocrUrl', methods=['POST'])
def ocrCaptchaUrl():
    try:
        data = request.get_data()
        print(data)
        json_data = json.loads(data.decode("UTF-8"), strict=False)
        allow = json_data.get("allow")
        url = json_data.get("url")

        rsp = urllib.request.urlopen(url)
        file_name = str(uuid.uuid1()) + ".jpg"
        file = open(file_name, "wb")
        file.write(rsp.read())
        file.close()
        res = reader.readtext(file_name, detail=0, allowlist=allow)
        os.remove(file_name)
        return '{"status":"200", "result":"' + res[0] + '"}'
    except Exception as e:
        print(e)
        return '{"status":"500"}'


# 接口的入参是验证码图片的base64
@app.route('/ocrBase64', methods=['POST'])
def ocrCaptchaBase64():
    try:
        data = request.get_data()
        json_data = json.loads(data.decode("UTF-8"), strict=False)
        base64_str = json_data.get("base64")
        allow = json_data.get("allow")
        image_data = base64.b64decode(base64_str)
        file_name = str(uuid.uuid1()) + ".jpg"
        file = open(file_name, "wb")
        file.write(image_data)
        file.close()
        res = reader.readtext(file_name, detail=0, allowlist=allow)
        os.remove(file_name)
        return '{"status":"200", "result":"' + res[0] + '"}'
    except Exception as e:
        print(e)
        return '{"status":"500"}'


if __name__ == '__main__':
    app.run(host='0.0.0.0', port=8181)
